package de.ohmhochschule.bme;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;

public class GameActivity extends Activity {
	public static final String STARTING_PLAYER = "de.ohmhochschule.bme.who_starts";
	public static final int STARTING_PLAYER_COMPUTER = 0;
	public static final int STARTING_PLAYER_HUMAN = 1;
	public static final char CHAR_COMPUTER = 'X';
	public static final char CHAR_HUMAN = 'O';

	private GameView gameView;
	private char data[] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
	private int availableMoves = 9;
	private char currentPlayer = CHAR_HUMAN;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		int player = getIntent().getIntExtra(STARTING_PLAYER,
				STARTING_PLAYER_COMPUTER);
		if ( player == STARTING_PLAYER_COMPUTER ) {
			currentPlayer = CHAR_COMPUTER;
			setNewPosition( (int)(Math.random()*9) );			
		} 
		gameView = new GameView(this);
		setContentView(gameView);
		gameView.requestFocus();
	}

	protected char getData(int i, int j) {
		return data[i + j * 3];
	}

	protected void setNewPosition(int i, int j) {
		setNewPosition(i + j * 3);
	}

	protected void setNewPosition(int i) {
		if (data[i] == ' ') {
			data[i] = currentPlayer;
			availableMoves--;

			if ( currentPlayer == CHAR_HUMAN ) {
				currentPlayer = CHAR_COMPUTER;		
				computerMoves();
				
			} else {
				currentPlayer = CHAR_HUMAN;								
			}
			
			checkIfGameIsOver();
			
		} else {
			unAllowedMove();
		}
	}

	private void unAllowedMove() {
		Toast toast = Toast.makeText(this, R.string.already_used,
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	private void computerMoves() {
		if ( availableMoves > 0 ) {
			int availPosition = findBestPosition();
			setNewPosition( availPosition );					
		}
	}

	private void checkIfGameIsOver() {
		if ( availableMoves == 0 ) {
			Toast toast = Toast.makeText(this, R.string.game_over,
					Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
	}

	private int findBestPosition() {
		int tempPos = 0;
		do {
			tempPos = (int)(Math.random()*9);			
		} while ( data[tempPos] != ' ' );
		return tempPos;
	}
}
